package middlewares

import (
	"arabApi/app/api/controllers/CFun"
	"arabApi/app/api/controllers/loginController"
	redis2 "arabApi/pkg/redis"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/spf13/cast"
	"time"
)

type user struct {
	Uid   string `json:"uid"`
	Token string `json:"token"`
}

func CheckLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		var out_uid string
		//fmt.Println(c.Request.Method)
		if c.Request.Method == "POST" {
			tuser := user{}
			if err := c.ShouldBindBodyWith(&tuser, binding.JSON); err != nil {
				CFun.Ajax_return_fail(c, CFun.WithMsg("解析错误"))
				return
			}
			token := redis2.Redis.Get(loginController.LoginRedis + tuser.Uid)
			if len(token) < 1 || token != tuser.Token {
				CFun.Ajax_return_fail(c, CFun.WithMsg("请重新登录"), CFun.WithCode(100))
				return
			}

			out_uid = tuser.Uid
		} else {
			uid := c.Query("uid")
			token1 := c.Query("token")
			token := redis2.Redis.Get(loginController.LoginRedis + uid)
			if len(token) < 1 || token != token1 {
				CFun.Ajax_return_fail(c, CFun.WithMsg("请重新登录"), CFun.WithCode(100))
				return
			}
			out_uid = uid
		}

		useMsg := new(loginController.Login).UserMsg(cast.ToInt64(out_uid))
		c.Set("userMsg", useMsg)
		redis2.Redis.Set("User_Name", out_uid, time.Second*500)
		// 处理请求
		c.Next()
	}
}
